var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


// 用于JWT认证
let {expressjwt:expressJWT} = require('express-jwt')

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var chuan = require('./routes/server');
// var event = require('./routes/coustpmerserver')
var cors = require('cors');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

const corsOptions = {
  origin: 'http://localhost:5173', // 允许前端的源
  methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
  credentials: true,
  optionsSuccessStatus: 204
};

app.use(cors(corsOptions));

app.use(cors())




app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/server', chuan);
// app.use('/event', event);


// 使用JWT认证中间件
app.use(
  expressJWT({
    secret:'abcdefg', //JWT密钥
    algorithms:['HS256']//使用的加密算法
  }).unless({
    path:[
      '/login2',
      '/faceLogin',
      '/login',
      '/get_sms',
      '/getHeritage',
      '/upload',
      '/get_sms',
      '/getType',
      '/getContent',
      '/order_Cate', 
      '/order_List',
      '/xiang/:id',
      '/address_Cate',
      '/address_List',
      '/address_Add',
      '/guanzhu_Cate',
      '/guanzhu_List',
      '/guandong_Cate',
      '/guandong_List',
      '/yuyue_Cate',
      '/yuyue_List',
      '/yuyue_xiang/:id',
      '/Cai_List',
      '/Cai_Cate',
      '/getshop',
      '/getcommodity',
      '/addtopic',
      '/addshequ',
      '/addtiezi',
      '/getshequ',
      '/gettiezi',
      '/gethuati',
      '/findtiezi',
      '/findtiezi2',
      '/findhuati',
      '/updatetiezi',
      '/addpinglun',
      '/getpinglun',
      '/getpinglun2',
      "/server/directUpload",
      "/server/upload",
      "/server/merge",
      "/server/verify",
      "/server/download/:fileName",
    ]
  })
)

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development'? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;